﻿using Dao;
using HospitalErpWinUI.BaseClass;
using HospitalErpWinUI.GlobalVar;
using HospitalErpWinUI.WinFormUiHelper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HospitalErpWinUI
{
    public partial class FormSetEnv : Form
    {
        protected DaoHelper _helper;
        public FormSetEnv()
        {
            InitializeComponent();
            init();
        }

        private void FormSetEnv_Load(object sender, EventArgs e)
        {
           
        }

        private void  init()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            this._helper = new DaoHelper();

            this.login_date.EditValue = G_User.user.LoginDate;

            LoadCompCode();
            FormHelper.ComboBoxeditAssignment(comp_code ,G_User.user.Comp_code);

            if(G_User.user.Mod_Level != 3)
            {
                this.copy_code.Visible = false;
                this.labelControl2.Visible = false;
                return;
            }
            
            LoadCopyCode();
            FormHelper.ComboBoxeditAssignment(copy_code ,G_User.user.Copy_code);
         
        }

        #region 访问数据
            private void LoadCompCode()
            {
                ServiceParamter serviceParamter = new ServiceParamter();
                serviceParamter.ServiceId = "sys_perm_comp_list";
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("mod_code", G_User.user.Module_code);
                serviceParamter.Paramters = dict;

                DataTable dt = _helper.ReadDictForSql(serviceParamter);
                List<string> objs = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    CodeValue codeValue = new CodeValue();
                    codeValue.Code = dt.Rows[i][0].ToString();
                    codeValue.Value = dt.Rows[i][1].ToString();
                    objs.Add(codeValue.Value);
                }
                comp_code.Properties.Items.AddRange(objs);


            }

            private void LoadCopyCode()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            serviceParamter.ServiceId = "sys_perm_copy_list";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("mod_code", G_User.user.Module_code);
            dict.Add("comp_code", G_User.user.Comp_code);
            serviceParamter.Paramters = dict;

            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            List<string> objs = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][0].ToString()+" "+dt.Rows[i][1].ToString();
                objs.Add(codeValue.Value);
            }
            copy_code.Properties.Items.AddRange(objs);


        }
            //获得登陆日期内的会计期间
            private DataTable Acct_get_login_date_period()
            {
                ServiceParamter serviceParamter = new ServiceParamter();
                serviceParamter.ServiceId = "acct_get_login_date_period";
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("comp_code", FormHelper.GetValueForComboBoxEdit(comp_code));
                dict.Add("copy_code", FormHelper.GetValueForComboBoxEdit(copy_code));
                //   login_date.Text
                dict.Add("login_date", DateTime.ParseExact(login_date.Text, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd"));
                serviceParamter.Paramters = dict;

                DataTable dt = _helper.ReadDictForSql(serviceParamter);
                return dt;
            }

            //获取系统是否已经启用
            private bool GetBusinessSystemStart()
            {
                ServiceParamter serviceParamter = new ServiceParamter();
                serviceParamter.ServiceId = "getBusinessSystemStart";
                Dictionary<string, string> dict = new Dictionary<string, string>();
                  dict.Add("mod_code", G_User.user.Module_name);
                  dict.Add("comp_code", FormHelper.GetValueForComboBoxEdit(comp_code));
                  dict.Add("copy_code", FormHelper.GetValueForComboBoxEdit(copy_code));
                  dict.Add("login_date", login_date.Text);
                serviceParamter.Paramters = dict;

                DataTable dt = _helper.ReadDictForSql(serviceParamter);
                return  Convert.ToInt16( dt.Rows[0][0]) == 1;
            }

        #endregion

            private void but_save_Click(object sender, EventArgs e)
            {
                G_User.user.Comp_code = FormHelper.GetValueForComboBoxEdit(comp_code);
                G_User.user.Copy_code = FormHelper.GetValueForComboBoxEdit(copy_code);
                G_User.user.LoginDate = login_date.Text;

                if(G_User.user.Mod_Level == 3)
                {
                    if (string.IsNullOrEmpty(copy_code.Text))
                    {
                        MessageForm.Warning("请设置要操作的账套！");
                        copy_code.Focus();
                        return;

                    }
                }
                DataTable dt = Acct_get_login_date_period();
                if (dt.Rows.Count != 0)
                {
                    if (!G_User.user.Module_name.Equals("sys"))
                    {
                        if (GetBusinessSystemStart())
                        {
                            MessageForm.Warning("选定年度系统没有启用！");
                            return;
                        }
                    }
                    string[] period = dt.Rows[0][0].ToString().Split(';');
                    G_User.user.Begin_date = Convert.ToDateTime(period[0]);
                    G_User.user.End_date = Convert.ToDateTime(period[1]);
                    G_User.user.Acct_year = dt.Rows[0][1].ToString();

                }
                else
                {
                    if (!G_User.user.Module_name.Equals("sys"))
                    {
                          MessageForm.Warning("选定日期没有期间信息！");
		                return;
                    }
                }
                SubmitEnv();
                this.Close();
            }

            private bool SubmitEnv()
            {
                G_User.user.Comp_code = FormHelper.GetValueForComboBoxEdit(comp_code);
                if (G_User.user.Module_name.Equals("sys"))
                {
                    G_User.user.Copy_code = "";
                }
                else
                {
                    G_User.user.Copy_code = FormHelper.GetValueForComboBoxEdit(copy_code);
                }

                /*
                   string url = ConfigurationManager.AppSettings["ServicesAdress"] + "/User/SetUserInf";                
                string ticString = JsonConvert.SerializeObject(G_User.user);
                byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
                string str = Convert.ToBase64String(inArray);
                 str = str.Replace("+", "%2B").Replace("+", "%2B"); ;

                 Dictionary<string, string> dict = new Dictionary<string, string>();
                 dict.Add("", str);

                try
                {
                    HttpHelper.CreateHttpPostResponse(url, dict);                  
                }
                catch (Exception e)
                {
                    MessageForm.Exception(e.Message);
                    return;
                }
                 */


                bool result = false;

                string ticString = JsonConvert.SerializeObject(G_User.user);
                byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
                string str = Convert.ToBase64String(inArray);
                str = str.Replace("+", "%2B").Replace("+", "%2B"); ;

                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("", str);

                string realUrl = ConfigurationManager.AppSettings["ServicesAdress"] + "/User/SetUserInf";       

                try
                {
                    string strResult = HttpHelper.CreateHttpPostResponse(realUrl, dict, G_User.user.Ticket,  "");
                    ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(strResult, typeof(ApiResultModel)) as ApiResultModel;

                    if (mode.IsSuccess)
                    {
                        result = true;
                    }
                    else
                    {
                        throw new Exception(mode.ErrorMessage);
                    }

                }
                catch (Exception e)
                {

                    MessageForm.Warning(e.Message);
                }
                return result;
            }

            private void but_quit_Click(object sender, EventArgs e)
            {
                try
                {
                    Properties.Settings.Default.Save();                   
                    Application.Exit();
                }
                catch
                {
                    Environment.Exit(0);
                } 
            }
       
    }
}
